// src/yu/filter/AuthFilter.java
package yu.filter;

@WebFilter("/*")
public class AuthFilter implements Filter {
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        String path = request.getRequestURI();

        // 放行登录相关资源
        if (path.endsWith("login.html") || path.endsWith("LoginServlet")
                || request.getSession().getAttribute("user") != null) {
            chain.doFilter(req, res);
        } else {
            response.sendRedirect("login.html");
        }
        // 在AuthFilter的doFilter方法开头添加：
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("autoLogin".equals(cookie.getName())) {
                    request.getSession().setAttribute("user", cookie.getValue());
                    break;
                }
            }
        }
    }
}